package group.program.utils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
@Component
public class OSSUtils {
    private String endpoint="https://oss-cn-hangzhou.aliyuncs.com";
    private String accessKeyId="LTAI5tC916ALWph43UdStsEe";
    private String accessKeySecret="h6NcSUmeo8jPY1bZKBV0HaTRPOncrA";
    private String buketName="hy-program";
    //上传文件到阿里云
    public String upload(MultipartFile file) throws IOException {
        //获取上传文件的输入流
        InputStream inputStream =file.getInputStream();
        //避免文件覆盖
        String originalFilename=file.getOriginalFilename();
        String fileName = UUID.randomUUID() +originalFilename.substring(originalFilename.lastIndexOf("."));
        //上传文件到OSS
        OSS ossClient =new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
        ossClient.putObject(buketName,fileName,inputStream);
        //文件访问路径
        String url=endpoint.split("//")[0]+"//"+buketName+"."+endpoint.split("//")[1]+"/"+fileName;
        //关闭OSSClient
        ossClient.shutdown();
        return url;
    }
}
